0%

Self-Learned Algorithms - 07

Self-Learned Algorithms - 07

This is my learning note about algorithms.

Reference


905.按奇偶排序数组

https://leetcode-cn.com/problems/sort-array-by-parity/

题解

  • 奇偶数的话维护双指针就可以了

解法

  • 按照模2的结果排序
1
2
A.sort(key = lambda x: x % 2)
return A
  • 奇数数组和偶数数组拼接
1
2
3
4
5
6
7
8
ans1 = []
ans2 = []
for i in A:
if i % 2 == 0:
ans1.append(i)
else:
ans2.append(i)
return ans1 + ans2
  • 双指针同向遍历
1
2
3
4
5
6
i = 0
for j in range(len(A)):
if A[j] % 2 == 0:
A[i], A[j] = A[j], A[i]
i += 1
return A
  • 双指针双向遍历
1
2
3
4
5
6
7
8
i, j = 0, len(A)-1
while i < j:
while A[i] % 2 == 0 and i < j:
i += 1
while A[j] % 2 == 1 and i < j:
j -= 1
A[i], A[j] = A[j], A[i]
return A